package me.atbar.moonlib.util;

import me.atbar.moonlib.Main;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 基本的工具类
 */
public class BasicUtils {

    private BasicUtils() {}

    public void callEvent(Event event) {
        Bukkit.getServer().getPluginManager().callEvent(event);
    }

    public void registerEvents(Listener listener) {
        Bukkit.getServer().getPluginManager().registerEvents(listener, Main.getInstance());
    }

    public void restart() {
        Bukkit.spigot().restart();
    }

    /**
     * 将玩家名转换为UUID
     * <p>
     * Convert player name to UUID
     *
     * @param name the player name
     * @return {@link UUID}, the name of the corresponding uuid
     */
    public UUID translateNameToUUID(String name) {
        final Player player = Bukkit.getPlayerExact(name);
        if (player != null) {
            return player.getUniqueId();
        } else {
            return UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes());
        }
    }

    public List<Item> getDropItem(World world) {
        List<Item> items = new ArrayList<>();
        world.getEntities().forEach((entity -> {
            if(entity.getType() == EntityType.DROPPED_ITEM) {
                items.add((Item) entity);
            }
        }));
        return items;
    }

    public void executeCommand(CommandSender sender, String command) {
        Bukkit.dispatchCommand(sender, command);
    }

}
